import axios from "axios";

//封装文件下载axios
const service = axios.create({
    responseType: 'arraybuffer'
})

//封装请求拦截器
service.interceptors.request.use(config => {
    config.headers['Authorization'] = window.sessionStorage.getItem('token')
    return config
}, error => {
    console.log(error)
})

//响应拦截器
service.interceptors.response.use(res => {
    const headers = res.headers
    let reg = RegExp(/application\/json/)
    if (headers['content-type'].match(reg)){
        //如果返回的是json的话就将其转换为json字符串
        res.data = unitToString(res.data)
    }else {
        //返回流的话就使用插件处理相应的流
        let fileDownload = require('js-file-download')
        //获取文件名
        let fileName = headers['content-disposition'].split(';')[1].split('filename=')[1]
        //获取contentType
        let contentType = headers['content-type']
        //解码防止中文乱码
        fileName = decodeURIComponent(fileName)
        //使用插件下载
        fileDownload(res.data, fileName, contentType)
    }

}, error => {
    console.log(error)
})

//解析为字符串
function unitToString(unitArray){
    let encodeString = String.fromCharCode.apply(null, new Uint8Array(unitArray))
    let decodedString = decodeURIComponent(escape(encodeString))
    return JSON.parse(decodedString)
}

let baseUrl = ''
//导出
export const downloadRequest = (url, params) => {
    return service({
        method: 'get',
        url: `${baseUrl}${url}`,
        data: params
    })
}

export default service
